package com.xigua.数组;

import java.util.*;

/**
 * @author LiRongHua
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2022/3/2715:40
 */
public class _15_三数之和 {

    public static void main(String[] args) {
        threeSum(new int[]{-1,0,1,2,-1,-4});
        int i = 1;
        System.out.println(1 == i++);
        System.out.println(1 == ++i);
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        for(int i = 0; i < nums.length - 2; i++){
            if (nums[i] > 0) break;
            if (i != 0 && nums[i] ==nums[i-1]) continue;
            int left = i+1;
            int right = nums.length-1;
            while (left<right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {
                    res.add(new ArrayList<>(Arrays.asList(nums[i], nums[left], nums[right])));
                    while (left < right && nums[left] == nums[++left]) ;
                    while (left < right && nums[right] == nums[--right]) ;
                } else if (sum > 0) {
                    while (left < right && nums[right] == nums[--right]) ;
                } else {
                    while (left < right && nums[left] == nums[++left]) ;
                }
            }
        }
        return res;
    }
}
